import 'dart:convert';

import 'package:hibrid_flutter/video_page/video_model.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'server_data.dart';

class VideoController {

  List<VideoModel>? dataList;
 Future<void> init() async {
   // 一级缓存判断为空，则执行二级
   dataList ??= await fetchVideoData();
 }



  // 从服务端拉取视频Json字符串类型表示的视频数据
  Future<List<VideoModel>> fetchVideoData() async{
   // 二级缓存找到直接使用
    SharedPreferences sp = await SharedPreferences.getInstance();
    var modelStr = sp.getString('videoModel');
    if (modelStr != null && modelStr.isNotEmpty) {
      var list = jsonDecode(modelStr) as List<dynamic>;
//      List<VideoModel> newList = [];
//      for (int i = 0; i < list.length; i ++) {
//        newList.add(VideoModel.fromJson(list[i]));
//      }
      return list.map((e) => VideoModel.fromJson(e)).toList();
    }
  // 二级缓存未找到，执行三级缓存
    var json = ServerData.fetchDataFromServer();
    sp.setString('videoModel', json);
    var list = jsonDecode(json) as List<dynamic>;
    return list.map((e) => VideoModel.fromJson(e)).toList();
  }
}